package com.qk.management.web.interceptor;

import com.qk.common.config.CurrentUserContextHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @author kaoM1Jy
 * @date 2025/10/11 15:39
 * @description:
 */
    @Slf4j
    @Component
    @SuppressWarnings("all")
    public class LoginCheckInterceptor implements HandlerInterceptor {
        // 请求头中名字叫token
        private static final String TOKEN_HEADER_NAME = "token";
        @Override
        public boolean preHandle(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Object handler) throws Exception {

            log.info("=========================拦截器处理线程名称是：{}",Thread.currentThread().getName());
            String token = request.getHeader(TOKEN_HEADER_NAME);
            if (Objects.isNull(token)) {
                log.info("请求头中没有token");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
            try {
                Claims claims = JwtUtils.parseToken(token);
                log.info("-----token验证成功-----");
                String username = claims.get("username", String.class);
                log.info("-----用户信息是：{}-----", username);
                Integer id = claims.get("id", Integer.class);
                CurrentUserContextHolders.set(id);
                log.info("-----用户id是：{}-----", id);
                return true;
            } catch (Exception e) {
                log.error("-----token验证失败-----", e);
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }

        }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}
